package com.codeduck.zk.client;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

/**
 * @author: <a href="mailto:codeduck@163.com">Codeduck</a>
 * @createDate: 2022-05-18
 */
@Component
@Slf4j
public class ZkConfig {

    private String address = "192.168.124.24:2181";
    private int sessionTimeout = 80000;

    private ZooKeeper zkClient = null;

    @Bean
    public ZooKeeper registerZookeeperClient () throws IOException {
        zkClient = new ZooKeeper(address, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                log.info(watchedEvent.getType() + "------" + watchedEvent.getPath());
                // watcher 监听节点时只生效一次，使用后需要再次设定watcher
                try {
                    List<String> children = zkClient.getChildren("/", true);
                    for (String child : children) {
                        log.info("zk根目录下的child信息 ## {} ##", child);
                    }
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        return zkClient;
    }
}
